package com.example.test.controller;

import com.example.test.bean.UserBean;
import com.example.test.bean.UserImgBean;
import com.example.test.service.UserService;
import com.example.test.utils.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
public class LoginController {

    @Resource
    UserService userService;

    @RequestMapping("/login")
    public String show(){
        return "login";
    }

    @RequestMapping(value = "/loginAction",method = RequestMethod.POST)
    public String login(String name, String password, HttpSession session){
        UserBean userBean = userService.loginIn(name,password);
        if(userBean!=null){
            session.setAttribute("user",userBean);
            return "success";
        }else {
            return "error";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "index";
    }
    @RequestMapping(value = "/register",method = RequestMethod.GET)
    public  String register(){
        return  "register";
    }
    @RequestMapping(value = "/registerUser",method = RequestMethod.POST)
    public String registerUser(UserBean userBean, HttpServletRequest request){
        int flag = userService.insertUser(userBean);

        UserImgBean userImgBean = new UserImgBean();
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        for (MultipartFile multipartFile : files) {
            if(multipartFile.isEmpty())
                continue;
            byte[] fileBytes = new byte[0];
            try {
                fileBytes = multipartFile.getBytes();
                String originalFilename = multipartFile.getOriginalFilename();
                originalFilename = originalFilename.substring(originalFilename.lastIndexOf("."));
                String fileName = UUID.randomUUID() + originalFilename;
                boolean bRet =   FileUtils.uploadFile(fileBytes, "static/upload/"+fileName);
                if (bRet == false)
                    continue;

                userImgBean.setId(0);
                userImgBean.setUser_id(userBean.getId());
                userImgBean.setImg("upload/"+fileName);
                int iFlag =  userService.insertUserImg(userImgBean);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if(flag == 1){
            return "login";
        }else {
            return "register";
        }
    }
}
